package com.zcx.test.controller;

import com.zcx.test.ProjecttestApplication;
import com.zcx.test.common.vo.ApiResult;
import com.zcx.test.pojo.Log;
import com.zcx.test.pojo.LogExample;
import com.zcx.test.pojo.User;
import com.zcx.test.service.LogService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;
/**
 * @author zhaochangxin
 * @date 2022/3/8 13:47
 * 日志控制层
 */
@RestController
@RequestMapping("/log")
@Api(tags = "日志模块")
public class LogController {
    private final static Logger logger = LoggerFactory.getLogger(ProjecttestApplication.class );
    // 常量定义
    private static final String LOG_QUERY_SUCCESS = "查询完毕";
    private static final String LOG_INSERT_SUCCESS = "插入成功";
    private static final String LOG_DELETE_SUCCESS = "删除成功";

    @Autowired
    LogService logService;
    /**
     * queryLogList 查询所有日志信息
     * @param logExample
     * @return
     */
    @ApiOperation(value = "查询所有日志")
    @RequestMapping("/list")
    public ApiResult queryLogList(LogExample logExample) {
        LogExample.Criteria criteria = logExample.createCriteria();
        criteria.andCreatedByIsNotNull();
        List<Log> logsList = logService.queryLogList(logExample);
        for (Log log : logsList) {
            logger.info(log.toString());
        }
        return ApiResult.success(LOG_QUERY_SUCCESS, logsList);
    }

    /**
     * @param user
     * @param msg
     * @return ApiResult
     * @throws UnknownHostException 插入日志 insertLog
     */
    @ApiOperation(value = "添加日志")
    @RequestMapping("/add")
    public ApiResult insertLog(User user, String msg) throws UnknownHostException {
        Log log = new Log();
        InetAddress addr = InetAddress.getLocalHost();
        log.setLoginIp(addr.getHostAddress());
        log.setLoginName(user.getUsername());
        log.setLoginMsg(msg);
        log.setCreatedBy(Long.valueOf(1));
        log.setCreatedDate(new java.sql.Date(new java.util.Date().getTime()));
        log.setOwner("zcx");
        logService.insertLog(log);
        return ApiResult.success(LOG_INSERT_SUCCESS);
    }

    /**
     * 删除日志 deleteLogById
     * @param ids
     * @return ApiResult
     */
    @ApiOperation(value = "删除日志")
    @RequestMapping("/delete/{ids}")
    public ApiResult deleteLogById(@PathVariable("ids") String ids) {
        logService.deleteLogById(ids);
        return ApiResult.success(LOG_DELETE_SUCCESS);
    }
}
